#include "ProxyEventHandlerImpl.h"
#include "FlowChart.h"
#include "../../include/GTProto.h"
#include "EndianCast.h"
#include "GateServerRoot.h"
#include "Proxy.h"


IProxyEventHanlder * CProxyEventHandlerFactory::Create( CProxy * pProxy)
{
    CProxyEventHandler * handler = new CProxyEventHandler(pProxy);
    return handler;
}


CProxyEventHandler::CProxyEventHandler( CProxy * pProxy ) : 
m_stateMachine(this)
{
    m_pProxy = pProxy;
    m_stateMachine.initiate();
}

//void CProxyEventHandler::OnCliConnected()
//{
//
//}

void CProxyEventHandler::OnCliDisconnected()
{
    _NotifyDBOffline();
}

void CProxyEventHandler::OnCliError( int32 error_code, const char * error_message )
{
    _NotifyDBOffline();
}

void CProxyEventHandler::OnSvrConnected()
{
    m_stateMachine.process_event(EvServerAccepted());
}

void CProxyEventHandler::OnSvrDisconnected()
{
    m_stateMachine.process_event(EvServerDisconnected());
}
//
//void CProxyEventHandler::OnSvrError( int32 error_code, const char * error_message )
//{
//    
//}

void CProxyEventHandler::OnCliReceive( const char * message, uint32 message_length )
{
    m_stateMachine.OnRcvCliMessage(message, message_length);
}

void CProxyEventHandler::OnSvrReceive( const char * message, uint32 message_length )
{
    m_stateMachine.OnRcvSvrMessage(message, message_length);
}

void CProxyEventHandler::OnRecvPipeMsg(utility::network::PIPEID pipeID, const char * message, uint32 message_length )
{
    m_stateMachine.OnRcvPipeMessage(pipeID, message, message_length);
}

CProxy * CProxyEventHandler::GetProxy()
{
    return m_pProxy;
}

void CProxyEventHandler::_NotifyDBOffline()
{
    if (m_pProxy)
    {
        char buf[sizeof(uint32) + sizeof(GT_NOTIFY_USER_OFFLINE_NTF_PKG)] = {0};
        *(uint32*)buf = htonl(GT_NOTIFY_USER_OFFLINE_NTF_ID);
        GT_NOTIFY_USER_OFFLINE_NTF_PKG * pkg = (GT_NOTIFY_USER_OFFLINE_NTF_PKG *)(buf + sizeof(uint32));
        pkg->nUserID = htonl(m_pProxy->GetUserID());
        pkg->nProxyID = htonll(m_pProxy->GetID());
        m_pProxy->SendPipeMsg(GateServerRoot::Instance()->GetDBServerPipeId(), buf, sizeof(buf), false);
    }

}


